package com.huajx.core;

import com.huajx.core.config.HbootConfig;
import com.huajx.core.config.HbootConfigManager;
import com.huajx.core.server.HbootServer;
import com.huajx.core.server.HbootServerManager;
import com.huajx.core.udp.UDPClientManager;
import com.huajx.core.web.HbootWebConfig;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Hboot {
    private static Hboot jboot = new Hboot();

    public static Hboot me() {
        return jboot;
    }

    private final static Map<String, HbootServer> webServers = new LinkedHashMap<>();

    public static void run(String... args) {
        parseArgs(args);
        jboot.scan();
        jboot.start();
    }
//
    HbootWebConfig webConfig;
    HbootConfig config;

    private void scan() {
        webConfig = config(HbootWebConfig.class);
        config = config(HbootConfig.class);

        HbootServerManager.me().scan();
        UDPClientManager.me().scan();
    }

    /**
     * 开始启动
     */
    private void start() {

        HbootServerManager.me().start();
        UDPClientManager.me().start();
    }

    /**
     * 获取配置信息
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T config(Class<T> clazz) {
        return HbootConfigManager.me().get(clazz);
    }

    /**
     * 读取配置文件信息
     *
     * @param clazz
     * @param prefix
     * @param <T>
     * @return
     */
    public static <T> T config(Class<T> clazz, String prefix) {
        return HbootConfigManager.me().get(clazz, prefix, null);
    }

    /**
     * 读取配置文件信息
     *
     * @param clazz
     * @param prefix
     * @param file
     * @param <T>
     * @return
     */
    public static <T> T config(Class<T> clazz, String prefix, String file) {
        return HbootConfigManager.me().get(clazz, prefix, file);
    }


    /**
     * 解析启动参数
     *
     * @param args
     */
    private static void parseArgs(String[] args) {
        if (args == null || args.length == 0) {
            return;
        }

        for (String arg : args) {
            int indexOf = arg.indexOf("=");
            if (arg.startsWith("--") && indexOf > 0) {
                String key = arg.substring(2, indexOf);
                String value = arg.substring(indexOf + 1);
                setBootArg(key, value);
            }
        }
    }
    private static Map<String, String> argMap;

    public static void setBootArg(String key, Object value) {
        if (argMap == null) {
            argMap = new HashMap<>();
        }
        argMap.put(key, value.toString());
    }

//    public static void main(String[] args) {
//        Hboot.run(args);
//    }
}
